<template>
  <div class="list_dataset">
    <div style="height:100%">
      <div class="dataset_list_content">
        <!-- content -->
        <div class="list_aside"
             v-show="hideSideBar">

            <div style="padding:0 16px">
            <el-input placeholder="Search"
                      prefix-icon="el-icon-search"
                      clearable
                      @input="keyWordsChange"
                      v-model="keyWords">
            </el-input>
          </div>
          <SaveQuickFilter v-if="$refs['filter-condition'] && $refs['integration-condition'] && $refs['sort-condition']"
                           :filter="$refs['filter-condition'].filterForm"
                           :order="$refs['sort-condition'].clomu_sort"
                           :type="pagePath"
                           :integratin="$refs['integration-condition'].integratinSelected"/>

          <div class="sort_checkbox_group">
            <div class="sort_checkbox"
               @click="selectCondit('sort')">
            <sortConditionComponent :conditionItem="conditionItem"
                                    @sortChange="listColmSort"
                                    @tabTitle="tabSelect"
                                    :options="options"
                                    ref="sort-condition"></sortConditionComponent>
            </div>
            <div class="sort_checkbox"
               @click="selectCondit('filter')">
            <filterConditionComponent :conditionItem="conditionItem"
                                      :configScript="configScript"
                                      :recordFilterType="recordFilterType"
                                      @tabTitle="tabSelectfilter"
                                      @filterProjectForm="listColmFilter"
                                      ref="filter-condition"></filterConditionComponent>
            </div>
            <div class="sort_checkbox">
            <integrationConditionComponent :integraGpHeihgt="integraGpHeihgt"
                                           :isReportAdd="isReportAdd"
                                           @setShowAllIntegrations="setShowAllIntegrations"
                                           @integrationGp="listColmIntegration"
                                           ref="integration-condition"></integrationConditionComponent>
          </div>
          </div>
        </div>
        <div class="list_ri_content flex flex-col">
          <QuickFilter ref="quick-filter"
                       :type="pagePath"
                       :baseOptions="quickFilterCallback()"
                       @event:add="handleAdd"
                       @event:change="handleChangeQuickFilter"
                       immediate
                       :loading.sync="quickFilterLoading"
                       v-model="selectedQuickFilter">
            <template v-slot:crumb>
              <Crumb :expand="hideSideBar"
                     @click="hideSideBar = !hideSideBar"/>
            </template>
          </QuickFilter>
          <div class="flex px-16 pt-16">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-circle-plus-outline"
                       v-if="$hasPermission('sys:report:add')"
                       @click="newReport">{{ dashboardType.includes('Scorecard')?$t('custom.report.newScorecard'):$t('custom.report.newReport') }}
            </el-button>
            <!-- <NoIntegration type="dashboard"
                           ref="no-integration"
                           :params="{...dataForm,...filterProject}"
                           :immediate="false"/> -->
          </div>
          <div class="flex-1  h-0 py-16 pl-16"
               v-loading="dataListLoading  || widgetLoading || quickFilterLoading">
            <cardList ref="cardList"
                      :comDataList="comDataList"
                      :isReportAdd="isReportAdd"
                      :configScript="configScript"
                      :pageTotal="pageTotal"
                      :size="size"
                      :current="current"
                      :currListPage="dataForm.current"
                      :currListSize="dataForm.size"
                      :selectedQuickFilter="selectedQuickFilter"
                      @deleteHandleItem="deleteHandleItem"
                      @emitCurrPage="emitCurrPageChange"
                      @emitCurrSize="emitCurrSizeChange"
                      @getSelectData="getSelectData"
                      @editHandle="editHandle"
                      @cloneHandle="cloneHandle"
                      @shareHandle="shareHandle"
                      @cardQuery="cardQuery"
                      @homepageHandle="homepageHandle"
                      v-if="!!comDataList.length"></cardList>
            <div v-else
                 class="flex flex-col items-center justify-center h-full">

              <div class="no_data_img"></div>
              <template v-if="selectedQuickFilter.id === 'report-Custom'">
                <div>No custom dashboard found</div>
                <div @click="toReportLibrary" v-if="!$route.path.includes('CrossTenant')"
                     class="widget-library--text cursor-pointer">Please click Template {{ dashboardType }}s to view the
                  prebuilt dashboard
                </div>
              </template>
              <template v-else-if="selectedQuickFilter.id !== 'report-Template'&&'report-Custom'">
                <div>No dashboard found</div>
                <div @click="toReportLibrary" v-if="!$route.path.includes('CrossTenant')"
                     class="widget-library--text cursor-pointer">Please click Template {{ dashboardType }}s to view the
                  prebuilt dashboard
                </div>
              </template>
              <template v-else>
                <div>No dashboard found</div>
              </template>
            </div>

          </div>
        </div>
      </div>

    </div>
    <ShareLinkDialog ref="share-link"
                     :resourceType="'Report'" @refreshTagList="refreshTagList"></ShareLinkDialog>
    <HomePageDialog ref="HomePageDialog"></HomePageDialog>
  </div>
</template>
<script>
// import { debounce } from 'lodash'
import mixinViewModule from '@/mixins/crud-view-module'
import sortConditionComponent from '@/components/viewComponents/sort-condition.vue'
import filterConditionComponent from '@/components/viewComponents/filter-condition.vue'
import cardList from '@/components/viewComponents/card-list.vue'
import integrationConditionComponent from '@/components/viewComponents/intergration-condition.vue'

import QuickFilter, { SaveQuickFilter, QuickFilterMixins, QuickFilterItem, Crumb } from '@/components/quick-filter'
// import { NoIntegration } from '@/components/no-integration'
import HomePageDialog from '@/components/homepage-dialog/homepage-dialog.vue'

export default {
  props: {
    parentRecordFilterType: {
      type: String
    },
    isLoadingDone: {
      type: Boolean
    },
    widgetLoading: {
      type: Boolean
    },
    isReportAdd: {
      type: Boolean
    },
    dashboardType: {
      type: String,
      default: function () {
        return 'Dashboards'
      }
    },
    device: {
      type: Boolean,
      default: false
    }
  },
  components: {
    sortConditionComponent,
    filterConditionComponent,
    integrationConditionComponent,
    cardList,

    QuickFilter,
    SaveQuickFilter,
    // NoIntegration,
    QuickFilterItem,
    Crumb,
    HomePageDialog
  },
  mixins: [mixinViewModule, QuickFilterMixins],
  data () {
    return {

      tabIndex: 2,
      mixinViewModuleOptions: {
        getDataListURL: '/web/reports/sys/report/list',
        getDataListURLCard: '/web/reports/sys/report/card-list',
        getDataListIsPage: false,
        deleteURL_other: '/web/reports/sys/report/',
        deleteIsBatch: false,
        exportURL: ''
      },
      dataForm: {
        // current: 1,
        // size: 10
      },
      options: [
        {
          value: 'name',
          label: 'Name'
        },
        {
          value: 'status',
          label: 'Status'
        },
        {
          value: 'business_type',
          label: 'Type'
        },
        {
          value: 'create_date',
          label: 'Created Date'
        },
        {
          value: 'creatorName',
          label: 'Creator'
        },
        {
          value: 'update_date',
          label: 'Last Modified'
        },
        {
          value: 'updateByName',
          label: 'Last Modified By'
        }
      ],
      keyWords: '',
      // keyWordsValue: '',

      conditionItem: '',
      hideSideBar: true,
      configScript: {
        id: 'id',
        name: 'name',
        status: 'status',
        description: 'description',
        businessType: 'businessType',
        icon: 'icon',
        // botNum: 'botNum',
        // modelNum: 'modelNum',
        integration: 'integration',
        createDate: 'createDate',
        creatorName: 'creatorName',
        updateDate: 'updateDate',
        updateByName: 'updateByName',
        lastSyncDate: 'lastSyncDate',
        ownerName: 'ownerName',
        Permission: 'report',
        tagList: 'tagList'
      },
      filterProject: {
        'order': [
          { 'field': 'update_date', 'sort': 'DESC' }
        ],
        'filter': {
          'type': [],
          'status': [],
          'createDate': {
            'from': '',
            'to': ''
          },
          'updateDate': {
            'from': '',
            'to': ''
          },
          'creator': [],
          'updateBy': []
        },
        'integrationGroup': []
      },
      integraGpHeihgt: null,
      viewValue: localStorage.getItem('reportview') ? localStorage.getItem('reportview') : 'List',
      viewValueList: [{ label: 'Grid', value: 'Grid', icon: 'cuifont icon_table' }, {
        label: 'List',
        value: 'List',
        icon: 'cuifont icon_list'
      }],
      recordFilterType: this.parentRecordFilterType,
      selectedQuickFilter: {
        id: `report-${this.parentRecordFilterType}`

      },
      quickFilterLoading: false
      // pageType: null
    }
  },

  computed: {
    // if (this.dashboardType === 'Internal Dashboards' || this.dashboardType === 'Internal Scorecard') {
    //   this.$set(this.dataForm, 'internal', true)
    // }
    // if (this.dashboardType === 'Scorecard Dashboards' || this.dashboardType === 'Internal Scorecard') {
    //   this.$set(this.dataForm, 'layoutType', 'scorecard_layout')
    // }
    pagePath () {
      if (this.dashboardType === 'Dashboards') {
        return 'report'
      } else if (this.dashboardType === 'Internal Dashboards') {
        return 'internal-report'
      } else if (this.dashboardType === 'Scorecard Dashboards') {
        return 'scorecard-report'
      } else if (this.dashboardType === 'Internal Scorecard') {
        return 'internal-scorecard'
      }
    },
    // nameType () {
    //   if (this.$route.path.includes('Internal')) {
    //     return 'internal Dashboard'
    //   }

    //   if (this.$route.path.includes('Scorecard')) {
    //     return 'scorecard Dashboard'
    //   }

    //   return 'Dashboard'
    // },
    comDataList () {
      var retdata = []
      retdata = this.dataList
      // if (this.IsInternal()) {
      //   retdata = this._.filter(retdata, { businessType: 'MSPbots Internal' })
      // } else {
      //   retdata = this._.reject(retdata, { businessType: 'MSPbots Internal' })
      // }
      // filter(data => !keyWordsValue || data.name.toLowerCase().includes(keyWordsValue.toLowerCase())).slice((currentPage-1)*pageSize,currentPage*pageSize)
      // retdata = retdata.filter(item => {
      //   if (this.keyWordsValue) {
      //     if (item.description) {
      //       return item.name.toLowerCase().includes(this.keyWordsValue.toLowerCase()) || item.description.toLowerCase().includes(this.keyWordsValue.toLowerCase())
      //     } else {
      //       return item.name.toLowerCase().includes(this.keyWordsValue.toLowerCase())
      //     }
      //   } else {
      //     return item
      //   }
      // })
      // if (this.device && retdata.length > 0) {
      //   retdata = retdata.filter(item => {
      //     return item.layoutType === 'report_layout' && item.businessType !== 'Template'
      //   })
      // }
      if (this.isReportAdd) {
        retdata = this._.reject(this._.reject(retdata, { id: '1338420673936867329' }), { id: '1357516578732232706' }, { id: '1357516578732232707' })
      }
      return retdata
    }
  },
  watch: {
    dataListLoading (val) {
      if (!val) {
        this.$emit('update:isLoadingDone', true)
      }
    }
    // pageType: {
    //   handler (val) {
    //     this.$set(this.dataForm, 'showAllIntegration', val === 'Internal Dashboards')
    //     this.$set(this.dataForm, 'internal', val === 'Internal Dashboards')

    //     if (val === 'Scorecard Dashboards') {
    //       this.$set(this.dataForm, 'layoutType', 'scorecard_layout')
    //     }
    //     if (val === 'Dashboards') {
    //       this.$set(this.dataForm, 'layoutType', 'report_layout')
    //     }
    //   },
    //   immediate: true
    // }
  },

  created () {
    this.$root.eventBus.$on('deleteReport', () => {
      this.cardQuery()
      // if (this.$refs['no-integration']) {
      //   this.$refs['no-integration'].refresh()
      // }
    })
    // if (this.$route.path.includes('Internal')) {
    //   this.pageType = 'Internal Dashboards'
    // } else if (this.$route.path.includes('Scorecard')) {
    //   this.pageType = 'Scorecard Dashboards'
    // } else {
    //   this.pageType = 'Dashboards'
    // }
  },
  mounted () {
    this.tabSelect({ tab: false, text: 'sort' })
  },
  methods: {
    homepageHandle (item) {
      this.$refs.HomePageDialog.init(item)
    },
    getSelectData (arr) {
      let temp = []
      temp = arr.map((item, index) => {
        return {
          resourceId: item.id,
          resourceName: item.name
        }
      })
      this.$emit('getSelectData', temp)
    },
    clearSelectData () {
      if (this.$refs.cardList) this.$refs.cardList.clearSelectData()
    },
    toReportLibrary () {
      this.selectedQuickFilter = {
        id: 'report-Template',
        name: this.$t('custom.reports.templateDashboards'),
        filterJson: {
          filter: {
            type: ['Template']
          }
        },
        close: false
      }
      this.handleChangeQuickFilter(this.selectedQuickFilter)
    },
    refreshTagList () {
      this.$refs['quick-filter'].getQuickFilters('integration')
    },
    quickFilterCallback () {
      let path = window.location.pathname

      if (path.indexOf('CrossTenant') !== -1) {
        return []
      }

      const basicOptions = [
        {
          id: 'my-Favorites',
          name: this.$t('custom.widget.myFavorites'),
          filterJson: {
            filter: {
              type: ['Custom', 'Template', 'Community']
            }
          },
          close: false
        },
        {
          id: `report-Custom`,
          name: this.$t('custom.reports.myReport'),
          filterJson: {
            filter: {
              type: ['Custom']
            }
          },
          close: false
        },
        {
          id: `report-Template`,
          name: this.$t('custom.reports.templateDashboards'),
          filterJson: {
            filter: {
              type: ['Template']
            }
          },
          close: false
        }
      ]
      if (this.$route.path === '/Dashboards') {
        basicOptions[2].filterJson.filter.type.push('Community')
      }

      return [...basicOptions]
    },
    tabSelect (val) {
      let height = document.querySelector('.dataset_list_content').offsetHeight
      if (val.text === 'sort' && val.tab) {
        this.integraGpHeihgt = height - 10 - 121 - 60 - 80
      }
      if (val.text === 'sort' && !val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 60 - 80
      }
      this.$forceUpdate()
    },
    tabSelectfilter (val) {
      let height = document.querySelector('.dataset_list_content').offsetHeight
      if (val.text === 'filter' && val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 80 - 428
      }
      if (val.text === 'filter' && !val.tab) {
        this.integraGpHeihgt = height - 10 - 60 - 60 - 80
      }
      this.$forceUpdate()
    },
    // keyWordsChange: debounce(function (val) {
    //   this.keyWordsValue = val
    //   if (this.$refs.cardList) this.$refs.cardList.scrollTop()
    // }, 1000),
    listColmSort (val) {
      this.filterProject.order = val
      if (window.CardListSource) window.CardListSource()
      this.cardQuery()
    },
    listColmFilter (val) {
      this.recordFilterType = undefined
      this.filterProject.filter = val
      if (window.CardListSource) window.CardListSource()
      this.cardQuery(null, 1)
    },
    listColmIntegration (val) {
      this.filterProject.integrationGroup = val
      if (window.CardListSource) window.CardListSource()
      this.cardQuery(null, 1)
    },
    setShowAllIntegrations (val) {
      this.dataForm.showAllIntegration = val

      if (window.CardListSource) window.CardListSource()
      this.cardQuery(null, 1)
    },
    loadComDataList () {
      this.pageSize += 10
    },
    selectCondit (val) {
      this.conditionItem = val
    },
    cloneHandle (row) {
      this.$emit('commandClick', 'Clone', row)
    },
    editHandle (row) {
      this.$emit('commandClick', 'Edit', row)
    },
    emitCurrPageChange (page) {
      this.dataForm.current = page
      this.cardQuery()
    },
    emitCurrSizeChange (size) {
      this.dataForm.size = size
      this.cardQuery()
    },
    newReport () {
      this.$emit('newReport')
    },
    deleteHandleItem (row) {
      this.$emit('commandClick', 'Delete', row)
    },
    changeShowAllIntegration (e) {
      if (this.$refs.cardList) this.$refs.cardList.scrollTop()
      this.cardQuery()
    }

  },
  beforeRouteLeave (to, from, next) {
    if (to.meta.name === from.meta.name) {
      if (this.$store.state.contentTabs.findIndex(item => item.name === to.name) > -1) {
        this.$set(
          this.$store.state.contentTabs,
          this.$store.state.contentTabs.findIndex(item => item.name === to.name),
          {
            ...this.$store.state.contentTabs[this.$store.state.contentTabs.findIndex(item => item.name === to.name)],
            title: to.meta.title
          }
        )
      }
    }
    next()
  }
}
</script>
<style lang="scss" scoped>
.list_dataset {
  height: 100%;

  .dataset_list_content {
    height: 100%;
    background-color: #fff;
    margin-top: 10px;
    border-radius: 4px;
    height: calc(100% - 60px);

    .list_aside {
      display: flex;
      flex-direction:column;
      height: 100%;
      width: 283px;
      float: left;
      padding: 16px 0px;
      box-shadow: 1px 0px 0px 0px #f0f0f0;
      overflow: hidden;
      transition: 1s width;
      .sort_checkbox_group {
        flex: 1;
        overflow-y: auto;
        // max-height: 620px;
      }
    }

    .list_ri_content {
      transition: 1s width;
      height: 100%;

      .no_data_img {
        width: 164px;
        height: 99px;
        margin-bottom: 5px;
        background-image: url("#{$--ossLink}/app/view_pageheader/dataset_nodate.png");
        background-repeat: no-repeat;
        background-size: 164px 99px;
        background-position: center;
      }

      .no_data_text {
        margin-bottom: 10px;
        height: 20px;
        font-size: 14px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.5);
        line-height: 20px;
      }

      .no_data_intro {
        width: 200px;
        height: 34px;
        font-size: 12px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.25);
        line-height: 17px;
        text-align: center;
        margin-bottom: 10px;
      }

      .widget-library--text {
        color: #17b3a3;
        text-decoration: underline;
      }
    }
  }
}
</style>
